package com.rpc.center.manager;

import com.rpc.center.entity.ConsumerNode;
import com.rpc.common.entity.HostInfoPair;
import lombok.Setter;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class RPCSubscribeManager {
    /**
     * 服务的订阅列表
     */
    private Map<String,List<ConsumerNode>> subscribeMap=new ConcurrentHashMap<>();

    /**
     * 添加订阅信息
     * @param serviceID
     * @param consumerNode
     */
    public void addSubscriber(String serviceID,ConsumerNode consumerNode){
        List<ConsumerNode> subscribeList=subscribeMap.getOrDefault(serviceID,null);
        if(subscribeList==null){
            subscribeList=new ArrayList<>();
        }
        subscribeList.add(consumerNode);
        subscribeMap.put(serviceID,subscribeList);
    }

    /**
     * 移除订阅信息
     * @param serviceID
     * @param consumerNode
     */
    public boolean removeSubscriber(String serviceID,ConsumerNode consumerNode){
        List<ConsumerNode> subscribeList=subscribeMap.getOrDefault(serviceID,null);
        if(subscribeList==null){
            return false;
        }
        return subscribeList.removeIf(host -> {
            if(host.getAddress().equals(consumerNode.getAddress())){
                return true;
            }else {
                return false;
            }
        });
    }

    public List<ConsumerNode> getSubscribeList(String serviceID){
        return subscribeMap.get(serviceID);
    }
}
